﻿Namespace DGZfP.EventPublisher
    Partial Class Settings
        Inherits DotNetNuke.Entities.Modules.PortalModuleBase

#Region "Fields and Properties"
        Private SourceSettings As SourceTypeSettings


        Protected Property GoogleCalendars() As System.Collections.Generic.IDictionary(Of String, String)
            Get
                If ViewState("GoogleCalendars") = Nothing Then
                    If Not (String.IsNullOrEmpty(txtUserName.Text) AndAlso String.IsNullOrEmpty(txtPassword.Text)) Then
                        Dim dic As Generic.IDictionary(Of String, String)
                        Try
                            dic = New GoogleCalendarController().GetCalendars(txtUserName.Text, txtPassword.Text)
                        Catch e As Exception
                            Skins.Skin.AddModuleMessage(Me, e.Message, Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                            dic = New Generic.Dictionary(Of String, String)
                        End Try
                        dic.Add("", ">>not found<<")
                        GoogleCalendars = dic
                        Return dic
                    End If

                End If
                Return Nothing
            End Get
            Set(ByVal value As System.Collections.Generic.IDictionary(Of String, String))
                ViewState("GoogleCalendars") = value
            End Set
        End Property

        Protected ReadOnly Property SourceTypes() As System.Collections.Generic.IDictionary(Of String, String)
            Get
                Dim dic As New Generic.SortedDictionary(Of String, String)
                For Each SourceType As String In [Enum].GetNames(GetType(SourceProvider.SourceType))
                    dic.Add(SourceType, Localization.GetString(SourceType, LocalResourceFile))
                Next
                Return dic
            End Get

        End Property

        Private Function First(ByVal keys As Generic.ICollection(Of String)) As String
            Dim x As Generic.IEnumerator(Of String) = keys.GetEnumerator
            x.MoveNext()
            Return x.Current
        End Function

#End Region



#Region "Page Event Handlers"
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                'LoadSourcesettingsControl()
                GridSources.DataKeyNames = New String() {"KeyID"}
                If Not IsPostBack Then
                    'SourceSettings.LoadSettings()
                    txtPassword.Text = CStrN(Settings(Setting.GooglePassWord))
                    txtPassword.Attributes.Add("value", CStrN(Settings(Setting.GooglePassWord)))
                    txtUserName.Text = CStrN(Settings(Setting.GoogleAccount))
                    txtIframe.Text = CStrN(Settings(Setting.GoogleHTML))
                    BindSources(False)
                    Localization.LocalizeGridView(GridSources, LocalResourceFile)

                End If
                AdjustSourceSettings()
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub


        Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

            MyBase.OnInit(e)
        End Sub
#End Region


#Region "Command Event Handlers"

        ''' <summary>
        ''' cmdCancel_Click runs when the cancel button is clicked
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click
            Try
                Response.Redirect(NavigateURL(), True)
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub


        ''' <summary>
        ''' cmdUpdate_Click runs when the update button is clicked
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpdate.Click
            Try
                If Page.IsValid Then
                    ' Update settings in the database

                    UpdateSettings()
                    ' Redirect back to the portal home page
                    Response.Redirect(NavigateURL(), True)
                End If
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

       
#End Region

#Region "Private Methods"
        Private Sub UpdateSettings()
            Dim objModules As New DotNetNuke.Entities.Modules.ModuleController
            objModules.UpdateModuleSetting(ModuleId, Setting.GoogleAccount, txtUserName.Text)
            objModules.UpdateModuleSetting(ModuleId, Setting.GooglePassWord, txtPassword.Text)
            objModules.UpdateModuleSetting(ModuleId, Setting.GoogleHTML, txtIframe.Text)
        End Sub

        Private Sub BindSources(ByVal NewSource As Boolean)
            Dim Sources As Generic.IList(Of SourceInfo) = SourceController.GetList(ModuleId)
            If NewSource Then
                Dim Source As New SourceInfo()
                Source.Google_Calendar_ID = First(GoogleCalendars.Keys)
                Source.Context = ""
                Source.Source_Type = First(SourceTypes.Keys)
                Sources.Add(Source)
                GridSources.EditIndex = Sources.Count - 1
            End If
            For Each source As SourceInfo In Sources
                If Not GoogleCalendars.Keys.Contains(source.Google_Calendar_ID) Then source.Google_Calendar_ID = ""
            Next

            GridSources.DataSource = Sources
            GridSources.DataBind()

        End Sub

        Private Sub AdjustSourceSettings()
            If Not String.IsNullOrEmpty(ViewState("SelectedType")) Then AdjustSourceSettings(ViewState("SelectedType"))
        End Sub
        Private Sub AdjustSourceSettings(ByVal SelectedType As String)
            SourceSettings = CType(LoadControl(SourceController.GetSettingsControlPath(SelectedType)), SourceTypeSettings)


            SourceSettings.ID = SelectedType
            'If SourceSettingsPlaceHolder.Controls.Count = 0 Then
            If SourceSettingsPlaceHolder.Controls.Count = 0 OrElse SourceSettingsPlaceHolder.Controls(0).ID <> SelectedType Then

                SourceSettingsPlaceHolder.Controls.Clear()
                SourceSettingsPlaceHolder.Controls.Add(SourceSettings)
            End If

            ViewState("SelectedType") = SelectedType
        End Sub

        Private Function GetSourceSettingsFromControls() As SourceInfo
            Dim row As GridViewRow = GridSources.Rows(GridSources.EditIndex)
            Dim id As Integer = Integer.Parse(CType(row.FindControl("hiddenKeyId"), HtmlInputHidden).Value)

            Dim source As SourceInfo
            If id = -1 Then
                source = New SourceInfo
                source.KeyID = id
                source.ModuleID = ModuleId
            Else
                source = SourceController.Get(id)
            End If

            source.Context = CType(row.FindControl("txtContext"), TextBox).Text
            source.Google_Calendar_ID = CType(row.FindControl("ddlCalendar"), DropDownList).SelectedValue
            source.Source_Type = CType(row.FindControl("ddlSourceType"), DropDownList).SelectedValue
            source.Active = CType(row.FindControl("chkActive"), CheckBox).Checked
            source.Source_Setting_100 = SourceSettings.Source_Setting_100
            source.Source_Setting_2000 = SourceSettings.Source_Setting_2000
            source.Source_Setting_50a = SourceSettings.Source_Setting_50a
            source.Source_Setting_50b = SourceSettings.Source_Setting_50b

            source.Mapping_ID = mapId.Text
            source.Mapping_Title = mapTitle.Text
            source.Mapping_Start = mapStart.Text
            source.Mapping_End = mapEnd.Text
            source.Mapping_Content = mapContent.Text
            source.Mapping_AllDay = mapAllDay.Text
            source.Mapping_Location = mapLocation.Text

            Return source
        End Function

        Private Sub SetSourceSettingsInControls(ByVal id As Integer)
            Dim source As SourceInfo
            If id = -1 Then
                source = New SourceInfo
            Else
                source = SourceController.Get(id)
            End If
            SourceSettings.Source_Setting_100 = source.Source_Setting_100
            SourceSettings.Source_Setting_2000 = source.Source_Setting_2000
            SourceSettings.Source_Setting_50a = source.Source_Setting_50a
            SourceSettings.Source_Setting_50b = source.Source_Setting_50b

            mapId.Text = source.Mapping_ID
            mapTitle.Text = source.Mapping_Title
            mapStart.Text = source.Mapping_Start
            mapEnd.Text = source.Mapping_End
            mapContent.Text = source.Mapping_Content
            mapAllDay.Text = source.Mapping_AllDay
            mapLocation.Text = source.Mapping_Location
        End Sub

        Private Sub UpdateCurrentSource()
            Dim source As SourceInfo = GetSourceSettingsFromControls()
            If source.IsNew Then
                SourceController.Add(source)
            Else
                SourceController.Update(source)
            End If
        End Sub
        Private Sub MapFields(ByVal Columns As DataColumnCollection)
            mapId.Columns = Columns
            mapTitle.Columns = Columns
            mapStart.Columns = Columns
            mapEnd.Columns = Columns
            mapContent.Columns = Columns
            mapLocation.Columns = Columns
            mapAllDay.Columns = Columns


            Dim isEditMode As Boolean = Not (Columns Is Nothing)
            mapId.EditMode = isEditMode
            mapTitle.EditMode = isEditMode
            mapStart.EditMode = isEditMode
            mapEnd.EditMode = isEditMode
            mapContent.EditMode = isEditMode
            mapLocation.EditMode = isEditMode
            mapAllDay.EditMode = isEditMode

        End Sub

#End Region



        Protected Sub cmdAddSource_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAddSource.Click
            BindSources(True)
            panFieldSettings.Visible = True
            MapFields(Nothing)
        End Sub

        Protected Sub GridSources_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridSources.RowCancelingEdit
            GridSources.EditIndex = -1
            BindSources(False)
            panFieldSettings.Visible = False
            MapFields(Nothing)
        End Sub

        Protected Sub GridSources_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridSources.RowCommand
            Select Case e.CommandName
                Case "SourceTypeChanged"
                    Dim row As GridViewRow = GridSources.Rows(GridSources.EditIndex)
                    Dim SelectedType As String = CType(row.FindControl("ddlSourceType"), DropDownList).SelectedValue
                    AdjustSourceSettings(SelectedType)
                    MapFields(Nothing)
                Case "Run"
                    Dim source As SourceInfo = SourceController.Get(CInt(e.CommandArgument))


                    Dim master = New Calendar.EventsByDataTable(SourceProvider.GetData(source), source.Context)
                    master.ColumnsMapping(Calendar.EventByDataRow.IdColumn) = source.Mapping_ID
                    master.ColumnsMapping(Calendar.EventByDataRow.StartColumn) = source.Mapping_Start
                    master.ColumnsMapping(Calendar.EventByDataRow.EndColumn) = source.Mapping_End
                    master.ColumnsMapping(Calendar.EventByDataRow.TitleColumn) = source.Mapping_Title
                    master.ColumnsMapping(Calendar.EventByDataRow.ContentColumn) = source.Mapping_Content
                    master.ColumnsMapping(Calendar.EventByDataRow.LocationColumn) = source.Mapping_Location
                    master.ColumnsMapping(Calendar.EventByDataRow.AllDayColumn) = source.Mapping_AllDay

                    Dim slave = New Calendar.EventsByGoogleCalendarFeed( _
                        New GoogleCalendarController().GetService(txtUserName.Text, txtPassword.Text), _
                        source.Google_Calendar_ID, master.LowestDate, source.Context)

                    slave.SynchroniseEvents(master)
                Case Else

            End Select
        End Sub

        Protected Sub GridSources_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridSources.RowDataBound
            If (e.Row.RowState And DataControlRowState.Edit) = DataControlRowState.Edit Then
                Dim row As GridViewRow = e.Row
                Dim ddlSourceType As DropDownList
                Dim cmdChangeSourceType As LinkButton
                ddlSourceType = CType(row.FindControl("ddlSourceType"), DropDownList)
                cmdChangeSourceType = CType(row.FindControl("cmdChangeSourceType"), LinkButton)
                'OnChange -> simulate click at invisible LinkButton cmdChangeFieldType, which fires an item command "SourceTypeChanged"
                ddlSourceType.Attributes("onChange") = "document.getElementById('" & cmdChangeSourceType.ClientID & "').click();"
                Dim id As Integer = Integer.Parse(CType(row.FindControl("hiddenKeyId"), HtmlInputHidden).Value)
                AdjustSourceSettings(ddlSourceType.SelectedValue)
                SetSourceSettingsInControls(id)
                MapFields(Nothing)
            End If

        End Sub

        Protected Sub GridSources_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridSources.RowDeleting
            Dim row As GridViewRow = GridSources.Rows(e.RowIndex)
            Dim id As Integer = Integer.Parse(CType(row.FindControl("hiddenKeyId"), HtmlInputHidden).Value)
            SourceController.Delete(id)
            BindSources(False)
            MapFields(Nothing)
        End Sub

        Protected Sub GridSources_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridSources.RowEditing


            GridSources.EditIndex = e.NewEditIndex
            BindSources(False)
            MapFields(Nothing)
            panFieldSettings.Visible = True
        End Sub

        Protected Sub GridSources_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridSources.RowUpdating
            UpdateCurrentSource()
            GridSources.EditIndex = -1
            BindSources(False)
            MapFields(Nothing)
            panFieldSettings.Visible = False
        End Sub

        Protected Sub cmdStartMapping_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStartMapping.Click
            Dim source As SourceInfo = GetSourceSettingsFromControls()
            Dim table As DataTable = SourceProvider.GetData(source)

            MapFields(table.Columns)
        End Sub
    End Class
End Namespace